package userserv

import (
	"codedef"
	"encoding/json"
	"log"
	"net/http"
)

const (
	downloadUrl   = "http://192.168.1.100:4001/apk/download/app-debug.apk"
	updateMessage = "fixed many bugs"
	versionCode   = 1
)

var (
	fileServerHandler = http.StripPrefix("/apk/download/",
		http.FileServer(http.Dir("D:\\Ocean\\FarmManager\\app\\build\\outputs\\apk")))
)

func downloadFile(w http.ResponseWriter, r *http.Request) {
	fileServerHandler.ServeHTTP(w, r)
}

func onGetLatestApkV(w http.ResponseWriter, r *http.Request) {
	log.Println("onGetLatestApkV")

	var apkv struct {
		Url           string `json:"url"`
		VersionCode   int    `json:"versionCode"`
		UpdateMessage string `json:"updateMessage"`
	}

	apkv.UpdateMessage = updateMessage
	apkv.VersionCode = versionCode
	apkv.Url = downloadUrl

	buf, err := json.Marshal(apkv)
	if err != nil {
		log.Println("onGetLatestApkV failed:", err)
		replyError(w, codedef.ERR_ENCODE)
		return
	}

	w.Write(buf)
}

func init() {
	myMux.muxHandlers.HandleFunc("/apk/latest", onGetLatestApkV)
	myMux.muxHandlers.HandleFunc("/apk/download/", downloadFile)
	myMux.ignoreToken["/apk/latest"] = true
}
